<template>
  <div>
    <div>
      <input type="text" v-model="newTodo" @keyup.enter="add"/>
      <select v-model="status" @change="handleChange">
        <option value="1">全部</option>
        <option value="2">已完成</option>
        <option value="0">未完成</option>
      </select>
    </div>

    <ul>
      <li v-for="item in pageList" :key="item.id" :class="{done: item.isDone}" @click="toggleStatus(item)">
        {{item.name}}
      </li>
    </ul>
  </div>
</template>
<script>
export default {
  data() {
    return {
      newTodo: '',
      status: '1',
      // 保存所有数据
      todoList: [
        { id: 1, name: "吃饭", isDone: true },
        { id: 2, name: "睡觉", isDone: false },
      ],
      // 从所有数据中过滤部分数据
      pageList: []
    };
  },
  created() {
   this.pageList = this.todoList
  },
  methods: {
    handleChange() {
      // console.log(this.status);
      // 注意，这里我们在切换数据的时候，一定不要去修改原数据todoList
      switch (this.status) {
        case '1':
          // 全部
          this.pageList = this.todoList
          break;
        case '2':
          // 已完成
          this.pageList = this.todoList.filter(item => item.isDone)
          break;
      
        default:
          // 未完成
          this.pageList = this.todoList.filter(item => !item.isDone)
          break;
      }
    },
    add() {
      let id
      if(this.todoList.length === 0) {
        id = 1
      } else {
        let ids = this.todoList.map(item => item.id)
        id = Math.max.apply(null, ids) + 1
      }
      let temp = {
        id,
        name: this.newTodo,
        isDone: false
      }
      this.todoList.push(temp)
      // 清空输入框
      this.newTodo = ''
    },
    toggleStatus(item) {
      item.isDone = !item.isDone
    }
  }
};
</script>
<style>
.done {
  text-decoration: line-through;
}
ul {
  font-weight: bold;
  font-size: 30px;
  list-style: none;
  margin: 0;
  padding: 0;
  background-color: skyblue;
  width: 240px;
}
li.done {
  background-color: rgb(154, 158, 160);
  opacity: .6;
}
li {
  padding: 10px 5px;
}
li:hover {
  background-color: rgb(51, 120, 148);
}
</style>